package com.zzt.spider.task;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzt.spider.model.entity.Episode;
import com.zzt.spider.model.entity.Series;
import com.zzt.spider.model.entity.SpiderSource;
import com.zzt.spider.model.mapper.EpisodeMapper;
import com.zzt.spider.model.mapper.SeriesMapper;
import com.zzt.spider.model.mapper.SpiderSourceMapper;
import com.zzt.spider.service.VideoPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CheckUploadTask {
    @Autowired
    private SeriesMapper seriesMapper;

    @Autowired
    private EpisodeMapper episodeMapper;

    @Autowired
    private SpiderSourceMapper spiderSourceMapper;

    @Value("${r2.accessKey}")
    private String accessKey;

    @Value("${r2.secretKey}")
    private String secretKey;

    @Value("${r2.endpoint}")
    private String endpoint;

    @Value("${r2.bucket}")
    private String bucket;

    @Autowired
    private VideoPlanService videoPlanService;

    @Scheduled(fixedDelay = 1800 * 1000 )
    public void testCheckR2Uploads() {
        AmazonS3 s3 = AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, "auto"))
                .withPathStyleAccessEnabled(true)
                .withCredentials(new AWSStaticCredentialsProvider(
                        new BasicAWSCredentials(accessKey, secretKey)))
                .build();
        List<Series> seriesList = seriesMapper.selectList(new LambdaQueryWrapper<Series>().eq(Series::getReadyFlag, 0));
        int missingCount = 0;

        for (Series series : seriesList) {
            log.info("正在检查: ID=" + series.getId() + ", 名称=" + series.getSeriesName());
            String url = series.getCoverImageUrl();
            String prefix = extractPrefix(url); // 如 2020/31438

            ListObjectsV2Request req = new ListObjectsV2Request()
                    .withBucketName(bucket)
                    .withPrefix(prefix + "/");

            ListObjectsV2Result result = s3.listObjectsV2(req);
            List<String> keys = result.getObjectSummaries().stream()
                    .map(S3ObjectSummary::getKey)
                    .collect(Collectors.toList());

            boolean hasCover = keys.stream().anyMatch(k -> k.endsWith("cover.jpg"));
            boolean hasTs = keys.stream().anyMatch(k -> k.endsWith("segment_0.ts"));

            if (!hasCover || !hasTs) {
                String idStr = url.split("/")[1];
                log.info("❌ 缺文件: ID=" + series.getId() + ", 名称=" + series.getSeriesName());
                spiderSourceMapper.update(new LambdaUpdateWrapper<SpiderSource>().set(SpiderSource::getState, 0).eq(SpiderSource::getId, Integer.parseInt(idStr)));
                episodeMapper.delete(new LambdaQueryWrapper<Episode>().eq(Episode::getSeriesId, series.getId()));
                seriesMapper.delete(new LambdaQueryWrapper<Series>().eq(Series::getId, series.getId()));
                missingCount++;
            } else {
                seriesMapper.update(new LambdaUpdateWrapper<Series>().set(Series::getReadyFlag, 1).eq(Series::getId, series.getId()));
            }
        }

        log.info("✅ 检查完毕，未完整上传的共 " + missingCount + " 条记录。");

        log.info("正在更新频道...");
        videoPlanService.updateChannel();
        log.info("✅ 更新频道完毕");
    }

    private String extractPrefix(String url) {
        if (url == null || url.isEmpty()) return "";
        String[] parts = url.split("/");
        if (url.startsWith("http")) {
            return parts[parts.length - 3] + "/" + parts[parts.length - 2];
        } else {
            return parts[0] + "/" + parts[1];
        }
    }
}
